<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, watch } from "vue";
import request from "../../utils/request";
import { ElNotification } from "element-plus";
import { IMG_URL } from "@/utils/imgStatic";
import { Delete, Plus, ZoomIn } from "@element-plus/icons-vue";
import moment from "moment";

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
const fileList = ref([]);
const upload = ref(null);

// 移除图片
const handledel = (file) => {
  fileList.value.forEach((s, index) => {
    if (s.url === file.url) {
      fileList.value.splice(index, 1);
    }
  });
};
//展示大图
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

//限制大小
//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changeUploadImg = (file) => {
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  if (!isJPG && !isPNG) {
    ElNotification.error("上传图片只能是 JPG 或者 PNG 格式!");
    // 取消时在文件列表中删除该文件
    upload.value.handleRemove(file);
    return isJPG || isPNG;
  } else if (file.size / 1024 / 1024 > 4) {
    ElNotification.error("单张图片大小不能超过4MB!");
    return false;
  } else {
    fileList.value.push(file);
  }
};

let breadList = []; // 路由集合
const route = useRoute();
const getBreadcrumb = (url) => {
  let matched = url.matched;
  //如果不是首页
  if ("Home" == matched[0].name) {
    matched[0].meta = { title: "系统首页" };
  }
  breadList = matched;
};
watch(
  route,
  (newValue, oldValue) => {
    getBreadcrumb(newValue);
  },
  { deep: true, immediate: true }
);
// 修改岗位信息
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    const formData = new FormData();
    fileList.value.forEach((value, index) => {
      formData.append("file", value.raw);
    });
    formData.append("jzId", ruleForm.jzId);
    formData.append("jzName", ruleForm.jzName);
    formData.append("salary", ruleForm.salary);
    formData.append("phonenumber", ruleForm.phonenumber);
    formData.append("content", ruleForm.content);
    formData.append("place", ruleForm.place);
    formData.append("grade", ruleForm.grade);
    formData.append("star", ruleForm.star);
    formData.append("category", ruleForm.category);
    formData.append("jzImg", ruleForm.jzImg);
    if (valid) {
      request
        .post("/jzxx/update", formData, {
          headers: {
            "Content-Type":
              "multipart/form-data;charset=UTF-8; boundary=<calculated when request is sent>",
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            getData(); //刷新查询
            formEl.resetFields(); //清除表单
            ElNotification({
              title: "更新成功",
              message: "成功更新用户信息",
            });
            centerDialogVisible.value = false;
            cancel(formEl);
          } else {
            ElNotification({
              title: "更新失败",
              message: "请联系管理员检查失败原因",
            });
          }
        })
        .catch((e) => {
          ElNotification({
            title: "更新失败",
            message: "请联系管理员检查失败原因",
          });
        });
    } else {
      ElNotification({
        title: "校验失败",
        message: "请重新填写信息",
      });
    }
  });
};
// 表单默认数据
const ruleForm = reactive({
  jzId: "",
  jzName: "",
  salary: "",
  phonenumber: "",
  content: "",
  place: "",
  jzImg: "",
  grade: "",
  star: "",
});
// 校验
const rules = reactive({
  jzName: [
    {
      required: true,
      message: "请输入岗位名",
      trigger: "blur",
    },
  ],
  salary: [
    {
      required: true,
      message: "请输入薪资",
      trigger: "blur",
    },
  ],
  phonenumber: [
    {
      required: true,
      message: "请输入联系电话",
      trigger: "blur",
    },
  ],
  content: [
    {
      required: true,
      message: "请输入介绍",
      trigger: "blur",
    },
  ],
  place: [
    {
      required: true,
      message: "请输入地址",
      trigger: "blur",
    },
  ],
  category: [
    {
      required: true,
      message: "请选择岗位类型",
      trigger: "change",
    },
  ],
  grade: [
    {
      required: true,
      message: "请输入招聘方信誉等级",
      trigger: "blur",
    },
  ],
  star: [
    {
      required: true,
      message: "请输入岗位评分",
      trigger: "blur",
    },
  ],
});
const ruleFormRef = ref();
const centerDialogVisible = ref(false);

const handleEdit = (index, row) => {
  centerDialogVisible.value = true;
  ruleForm.jzId = row.jzId;
  ruleForm.jzName = row.jzName;
  ruleForm.place = row.place;
  ruleForm.star = row.star;
  ruleForm.grade = row.grade;
  ruleForm.category = row.category;
  ruleForm.salary = row.salary;
  ruleForm.phonenumber = row.phonenumber;
  ruleForm.content = row.content;
  ruleForm.jzImg = row.jzImg;
  JSON.parse(row.jzImg).forEach((item) => {
    fileList.value.push({
      url: `${IMG_URL}${item}`,
    });
  });
};
// 查询信息
const query = reactive({
  currentPage: 1,
  pageSize: 2,
});
const tableData = ref([]);
const totalCount = ref(0);
// 获取表格数据
const getData = () => {
  request
    .request({
      url: "/jzxx/getAllJzxxByPage",
      params: {
        category: query.category,
        jzName: query.jzName,
        currentPage: query.currentPage,
        pageSize: query.pageSize,
      },
      method: "get",
    })
    .then((res) => {
      //获取当前页的数据
      
      console.log("res.data.data.rowsres.data.data.rowsres.data.data.rows",res.data.data.rows)
      tableData.value = res.data.data.rows;
      console.log( tableData.value)
      //获取总记录数
      totalCount.value = res.data.data.count;
    })
    .catch((e) => {
      console.log(e);
    });
};
getData();
// 查询操作
const handleSearch = () => {
  getData();
};
// 分页导航
const handleCurrentChange = (val) => {
  query.currentPage = val;
  getData();
  // console.log(val);
};
// 删除操作
const handleDelete = (index, row) => {
  request
    .request({
      url: "/jzxx/delete",
      method: "get",
      params: {
        jzId: row.jzId,
        jzImg: row.jzImg,
      },
    })
    .then((res) => {
      if (res.data.msg == "success") {
        ElNotification({
          title: "删除成功",
          message: "成功删除用户信息",
        });
        getData();
      } else {
        ElNotification({
          title: "删除失败",
          message: "请联系管理员检查失败原因",
        });
      }
    })
    .catch((e) => {
      ElNotification({
        title: "删除失败",
        message: "请联系管理员检查失败原因",
      });
    });
};

let categoryData = reactive([]);
//获取分类数据
const getCategory = () => {
  request
    .request({
      url: "/category/getAllCategory",
      method: "get",
    })
    .then((res) => {
      //获取数据
      res.data.data.forEach((e) => {
        categoryData.push(e);
      });
    })
    .catch((e) => {
      console.log(e);
    });
};
getCategory();
//清空数据
const cancel = (formEl) => {
  centerDialogVisible.value = false;
  fileList.value = [];
};
</script>

<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
          >{{ item.meta.title }}</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-select
          v-model="query.category"
          placeholder="岗位分类"
          class="handle-select mr10"
        >
          <el-option label="全部岗位" key="" value=""></el-option>
          <el-option
            v-for="(item, index) in categoryData"
            widget="150"
            :key="index"
            :label="item.catName"
            :value="item.catId"
          >
          </el-option>
        </el-select>
        <el-input
          v-model="query.jzName"
          placeholder="岗位名"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
      </div>
      <!-- 表格 -->
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column
          prop="jzId"
          label="ID"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="jzName"
          label="兼职岗位名称"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          label="岗位类型"
          width="110"
          align="center"
          prop="category"
        >
          <template #default="scope">
            {{
              categoryData.filter((e) => {
                return scope.row.category == e.catId;
              })[0]?.catName
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="salary"
          label="薪资"
          width="110"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="phonenumber"
          label="联系电话"
          width="110"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="content"
          label="详情"
          width="300"
          align="center"
        ></el-table-column>
        <el-table-column prop="star" label="评分" width="180" align="center">
          <template #default="scope">
            <el-rate
              v-model="scope.row.star"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}分"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="grade"
          label="招聘方信誉等级"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column label="岗位图片" width="250" align="center">
          <template #default="scope">
            <el-carousel
              height="100px"
              with="100px"
              trigger="click"
              :autoplay="false"
              indicator-position="none"
            >
              <el-carousel-item
                v-for="(item, index) in JSON.parse(scope.row.jzImg)"
                :key="index"
              >
                <img :src="`${IMG_URL}${item}`" width="300" height="100" />
              </el-carousel-item>
            </el-carousel>
          </template>
        </el-table-column>
        <el-table-column
          prop="place"
          label="地址"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column label="发布时间" width="120" align="center">
          <template #default="scope">
            {{ moment(scope.row.effectTime).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="140" align="center">
          <template #default="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row, true)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定要删除此岗位"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-if="totalCount"
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          layout="prev, pager, next, jumper"
          :total="totalCount"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 岗位信息编辑 -->
    <el-dialog
      v-model="centerDialogVisible"
      title="岗位信息编辑"
      width="40%"
      :before-close="cancel"
    >
      <el-scrollbar height="300px">
        <div>
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            status-icon
          >
            <el-form-item label="兼职岗位名称" prop="jzName">
              <el-input v-model="ruleForm.jzName" />
            </el-form-item>
            <el-form-item label="薪资" prop="salary">
              <el-input v-model="ruleForm.salary" type="textarea" autosize />
            </el-form-item>  
            <el-form-item label="联系电话" prop="phonenumber">
              <el-input v-model="ruleForm.phonenumber" type="textarea" autosize />
            </el-form-item>
            <el-form-item label="介绍" prop="content">
              <el-input v-model="ruleForm.content" type="textarea" autosize />
            </el-form-item>
            <el-form-item label="地址" prop="place">
              <el-input v-model="ruleForm.place" type="textarea" autosize />
            </el-form-item>
            <el-form-item label="岗位类型" prop="category">
              <el-select
                v-model="ruleForm.category"
                placeholder="岗位分类"
                class="handle-select mr10"
              >
                <el-option label="全部岗位" key="" value=""></el-option>
                <el-option
                  v-for="(item, index) in categoryData"
                  widget="150"
                  :key="index"
                  :label="item.catName"
                  :value="item.catId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="招聘方信誉等级" prop="grade">
              <el-select
                v-model="ruleForm.grade"
                class="m-2"
                placeholder="请选择等级"
              >
                <el-option key="0" value="A" />
                <el-option key="1" value="B" />
                <el-option key="2" value="C" />
                <el-option key="3" value="D" />
                <el-option key="4" value="暂无" />
              </el-select>
            </el-form-item>
            <el-form-item label="岗位评分" prop="star">
              <el-input type="number" max="5" min="1" v-model="ruleForm.star" />
            </el-form-item>
            <el-form-item label="选择图片">
              <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-remove="handledel"
                :on-change="changeUploadImg"
                ref="upload"
                :file-list="fileList"
                :multiple="true"
                name="file"
                v-model="fileList"
                :limit="3"
              >
                <el-icon><Plus /></el-icon>
                <template #file="{ file }">
                  <div>
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <el-icon><zoom-in /></el-icon>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handledel(file)"
                      >
                        <el-icon><Delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
                <template #tip>
                  <div class="el-upload__tip">
                    只能上传一张图片,且单张图片大小不能超过4MB
                  </div>
                </template>
              </el-upload>
              <!--  放大的图片  -->
              <el-dialog v-model="dialogVisible" top="7vh">
                <img
                  w-full
                  :src="dialogImageUrl"
                  alt="Preview Image"
                  style="width: 100%; height: auto"
                />
              </el-dialog>
            </el-form-item>
          </el-form>
        </div>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >更新</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
          <el-button @click="cancel(ruleFormRef)">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
